#!/usr/bin/python
# -*- coding: utf8 -*-

from md5 import md5
from pymylib.lib.base import *
from pymylib.model import Session, User
from pymylib.lib.apihelper import *
from pymylib.lib.utils import *
from mako.lookup import TemplateLookup
from pylons.templating import render, render_response
from __init__ import perPage

'''class permObj(object):
            def __init__(self):
                self.libUser = False
                self.librarianUser = False
                self.editClassificators = False
                self.adminAccess = False'''

                
class UsersController(BaseController):
    template_prefix = '/users'
    
    def __before__(self):
        if 'user' in session:
            if session['user'] == 'anonymous':
                session['path_before_login'] = request.path_info
                session.save()
                return redirect_to(h.url_for(controller='login'))
        else: return redirect_to(h.url_for(controller='login'))

    def __check_permitions__(self):
        """Check for permitions"""

        # Зарегистрирован-ли пользователь в системе?
        if self.requires_auth and session['user'] == 'anonymous':
            c.error = "Необходимо выполнить вход в систему!"
            return False
        
        if session['adminAccess']:
            return True
        else: c.error = "Нет прав на выполнение этой операции!"

    def index(self):
        redirect_to(action='list')

    def list(self):
        c.pageTitle = unicode('Пользователи системы', encoding='utf8')
        c.formCaption = c.pageTitle
        c.curPage = 0

        user_q = Session.query(User)
        try:
            c.curPage = int(request.params['pg'])-1
            c.users = list(user_q.all()[perPage*c.curPage:perPage*(c.curPage+1)])
        except:
            c.users = list(user_q.limit(perPage))

        ''' Получим страницы с диапазоном заданным perPage '''
        c.pages = []
        i = 0
        for cat in c.users[:int(user_q.count()/perPage)+1]:
            i = i+1
            c.pages.append(i)
        
        if len(c.pages) == 1:
            c.pages = None

        ''' ---------------------------------------------- '''
        c.currentUser = None
        c.user_id = session['user_id']
        c.user_name = session['fio']
            
        return render_response(self.template_prefix + '/list.myt')

    def select(self):
        c.pageTitle = unicode('Выбор пользователя', encoding='utf8')
        c.formCaption = c.pageTitle
        c.curPage = 0

        user_q = Session.query(User)
        try:
            c.curPage = int(request.params['pg'])-1
            c.users = list(user_q.all()[perPage*c.curPage:perPage*(c.curPage+1)])
        except:
            c.users = list(user_q.limit(perPage))

        ''' Получим страницы с диапазоном заданным perPage '''
        c.pages = []
        i = 0
        for cat in c.users[:int(user_q.count()/perPage)+1]:
            i = i+1
            c.pages.append(i)
        
        if len(c.pages) == 1:
            c.pages = None
            
        return render_response(self.template_prefix + '/select.myt')
    
    def fullview(self, id):
        user_q = Session.query(User)
        c.users = user_q.get_by(id=id)
               
        return render_response(self.template_prefix + '/fullinfo.myt')

    
    def edit(self, id):
        class permObj(object):
            def __init__(self):
                self.libUser = False
                self.librarianUser = False
                self.editClassificators = False
                self.adminAccess = False

        user_q = Session.query(User)
        c.users = user_q.get_by(id=id)

        
        c.permObj = permObj()

        c.permObj.libUser = CheckBit(c.users.permitions, 3)
        c.permObj.librarianUser = CheckBit(c.users.permitions, 2)
        c.permObj.editClassificators = CheckBit(c.users.permitions, 1)
        c.permObj.adminAccess = CheckBit(c.users.permitions, 0)

        return render_response(self.template_prefix + '/edit.myt')
        
    def update(self, id):
        user_q = Session.query(User)        
        user_obj = user_q.get_by(id=id)

        if request.params['fio'] == "": raise 'Поле "ФИО" должно быть заполнено'
        else: user_obj.fio = request.params['fio']

        if request.params['pasport'] == "": user_obj.pasport = None
        else: user_obj.pasport = request.params['pasport']

        if request.params['address'] == "": raise 'Поле "Адрес" должно быть заполнено'
        else: user_obj.address = request.params['address']

        if request.params['email'] == "": user_obj.email = None
        else: user_obj.email = request.params['email']

        if request.params['zip'] == "": user_obj.zip = None
        else: user_obj.zip = request.params['zip']

        if request.params['phone'] == "": user_obj.phone = None
        else: user_obj.phone = request.params['phone']

        #if request.params['password'] == "": user_obj.password = None
        #else: user_obj.password = md5(request.params['password']).hexdigest()
        
        user_obj.permitions = 0
        try:
            if request.params['libUser']:
                user_obj.permitions = SetBit(user_obj.permitions, 3)
        except: pass

        try:
            if request.params['librarianUser']:
                user_obj.permitions = SetBit(user_obj.permitions, 2)
        except: pass

        try:
            if request.params['editClassificators']:
                user_obj.permitions = SetBit(user_obj.permitions, 1)
        except: pass

        try:
            if request.params['adminAccess']:
                user_obj.permitions = SetBit(user_obj.permitions, 0)
        except: pass

        if request.params['note'] == "": user_obj.note = None
        else: user_obj.note = request.params['note']

        user_obj.photo = None

        try:
            Session.commit()
        except:
            Session.rollback()
            raise "Ошибка при сохранении в базу данных"
        
        redirect_to('../list')
        
    def add(self):        
        c.users = None

        return render_response(self.template_prefix + '/edit.myt')

    def create(self):
        new_user = User()
        
        if request.params['fio'] == "": raise 'Поле "ФИО" должно быть заполнено'
        else: new_user.fio = request.params['fio']

        if request.params['pasport'] == "": new_user.pasport = None
        else: new_user.pasport = request.params['pasport']

        if request.params['address'] == "": raise 'Поле "Адрес" должно быть заполнено'
        else: new_user.address = request.params['address']

        if request.params['email'] == "": new_user.email = None
        else: new_user.email = request.params['email']

        if request.params['zip'] == "": new_user.zip = None
        else: new_user.zip = request.params['zip']

        if request.params['phone'] == "": new_user.phone = None
        else: new_user.phone = request.params['phone']

        if request.params['user_name'] == "": raise 'Поле "Имя пользователя" должно быть заполнено'
        else: new_user.user_name = request.params['user_name']

        if request.params['password'] == "": new_user.password = None
        else: new_user.password = md5(request.params['password']).hexdigest()
	#        if request.params['password'] == "": new_user.password = None
	#        else: new_user.password = request.params['password']
        
        new_user.permitions = 0
        try:
            if request.params['libUser']:
                new_user.permitions = SetBit(new_user.permitions, 3)
        except: pass

        try:
            if request.params['librarianUser']:
                new_user.permitions = SetBit(new_user.permitions, 2)
        except: pass

        try:
            if request.params['editClassificators']:
                new_user.permitions = SetBit(new_user.permitions, 1)
        except: pass

        try:
            if request.params['adminAccess']:
                new_user.permitions = SetBit(new_user.permitions, 0)
        except: pass

        if request.params['note'] == "": new_user.note = None
        else: new_user.note = request.params['note']

        new_user.photo = None

        try:                        
            Session.save(new_user)
            Session.commit()
        except:
            Session.rollback()
            raise "Ошибка при сохранении в базу данных"
        
        redirect_to('list')

    def delete(self, id):
        user_q = Session.query(User)
        user_obj = user_q.get_by(id=id)
        
        try:
            Session.delete(user_obj)
            Session.commit()
        except:
            Session.rollback()
            raise "Ошибка при удалении пользователя из базы данных. Возможно этот пользователь имеет незакрытые заказы!"
        
        redirect_to('../list')

